#include <iostream>

using namespace std;

/**
 * Definition for singly-linked list.
 */
struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:
    // Challenge: do this in one scan
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if (!head || !head->next) return nullptr;
        ListNode* fast = head, * slow = head;

        for (int i=0; i<n; i++) fast = fast->next;
        if (!fast) return head->next;  // 特殊处理：删除头结点
        while (fast->next) {
            fast = fast->next;
            slow = slow->next;
        }
        slow->next = slow->next->next;
        return head;
    }

    int curr = 0;
    ListNode* removeNthFromEndRecursive(ListNode* head, int n) {
        if (!head) return nullptr;
        head->next = removeNthFromEndRecursive(head->next, n);
        if (n==++curr) return head->next;
        return head;
    }
};
